package org.example.aidemo.function;

import org.example.aidemo.pojo.Order;
import org.example.aidemo.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.function.Function;

@Component
public class OrderAddFunction implements
        Function<OrderAddFunction.Request, OrderAddFunction.Response> {
    @Autowired
    private OrderService orderService ;
    private static final Logger logger = LoggerFactory.getLogger(OrderAddFunction.class);
    @Override
    public Response apply(Request request) {
        try {
            int order = orderService.addOrder(request.name(),request.username(),request.address(),LocalDateTime.now());
            if (order != 0) {
                return new Response(
                        request.name(),
                        request.username(),
                        request.address(),
                        LocalDateTime.now(),
                        "订单创建成功"
                );
            } else {
                return new Response(
                        "订单创建失败",
                        "未知",
                        "未知",
                        LocalDateTime.now(),
                        "订单创建错误"
                );
            }
        } catch (Exception e) {
            logger.error("订单创建过程中发生异常", e);
            return new OrderAddFunction.Response(
                    "新增异常",
                    "错误",
                    "错误",
                    LocalDateTime.now(),
                    "订单创建错误"
            );
        }
    }
    public record Request(String name, String username, String address) {}
    public record Response(String name, String username, String address, LocalDateTime createTime,String msg) {
        public Response(Order order,String msg) {
            this(
                    order.getName(),
                    order.getUsername(),
                    order.getAddress(),
                    order.getCreateTime(),
                    msg
            );
        }
    }
}